package com.leetcode.Offer;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class JZ32_I {
    public int[] levelOrder(TreeNode root) {
        //广度搜索
        if (root == null) {
            return new int[]{};
        }
        Queue<TreeNode> treeNodeQueue = new LinkedList<>();
        treeNodeQueue.add(root);

        ArrayList<Integer> list = new ArrayList<>();

        while (!treeNodeQueue.isEmpty()) {
            TreeNode peek = treeNodeQueue.poll();
            list.add(peek.val);
            if (peek.left != null) {
                treeNodeQueue.add(peek.left);
            }
            if (peek.right != null) {
                treeNodeQueue.add(peek.right);
            }
        }
        // list.toArray(new Integer[list.size()]); 其中参数必须为引用类型
        int[] ints = new int[list.size()];
        int a = 0;
        for (Integer integer : list) {
            ints[a++] = integer;
        }
        return ints;
    }
}
